package com.luxx.controller;

import com.luxx.dao.DishDao;
import com.luxx.dto.TextMessage;
import com.luxx.service.ChatService;
import com.luxx.service.TestService;
import com.luxx.util.XMLUtil;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by luxx on 2018/1/15 0015.
 */
@RestController
public class WXController {


    @RequestMapping(value = "/wx", method = RequestMethod.GET)
    public void getDishes(HttpServletRequest request,
                          HttpServletResponse response,
                          @RequestParam String signature,
                          @RequestParam String timestamp,
                          @RequestParam String nonce,
                          @RequestParam String echostr
    ) throws IOException {
        response.getWriter().write(echostr);
    }

    @RequestMapping(value = "/wx", method = RequestMethod.POST)
    public void chat(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Map<String, String> map = XMLUtil.xmlToMap(request);
            String fromUserName = map.get("FromUserName");
            String toUserName = map.get("ToUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");
            System.out.println(toUserName);
            System.out.println(fromUserName);
            String message = null;

            if ("text".equals(msgType)) {
                TextMessage text = new TextMessage();
                text.setFromUserName(toUserName);
                text.setToUserName(fromUserName);
                text.setMsgType("text");
                text.setCreateTime(System.currentTimeMillis());
                String reply = chatService.chat(content, fromUserName);
                if (reply == null || "".equals(reply)) {
                    reply = "一脸懵逼^(*￣(oo)￣)^";
                }
                text.setContent(reply);
                message = XMLUtil.texMessageToXml(text);
            }
            System.out.println(message);
            response.getWriter().write(message);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private DishDao dishDao;
    @Autowired
    private TestService testService;
    @Autowired
    private ChatService chatService;
}
